
<template>
    <div class="pres-land-overall-comp">
         <TitleBox type=2>
            <template #titlecont>
                <span v-lang="{lang: controlSto.language, lgid: -29}">Overall network</span>
            </template>
        </TitleBox>

        <!-- TODO 就一个1个关系图 -->
        <div class="cont-box" ref="networkDiv">
            <CombinationDiagram
                :dragramTypeList="dragramTypeList"
                @changeTabs="changeTabs"
                :selectTab="selectTab"
                :diagramLenList="dataGraph.diagramLenList"
                @changeShow="changeShow"
                :typeGraph="1"
                :graphRange="graphRange"
                @changeSlider="changeSlider"
                :maxRange="maxRange"
                :dataGraph="dataGraph.data"
                :linksGraph="dataGraph.links"
                :dataTable="dataTable"
                :uiCodeDowm="uiCodeDowm"
								:hotMapX="dataGraph.hotMapX"
								:hotMapY="dataGraph.hotMapY"
								:hotMapData="dataGraph.hotMapData"
								:hotMaxRange="dataGraph.hotMaxRange"
								:templateList="dataTable.templateList"
								@toClkItem="toClkItem"
								:para="dataTable.para"
								:condPage="condPage"
								@chgSize="chgSize"
								@chgCurrnt="chgCurrnt"
								:loading="isLoading"
								:loadingNetWork="dataTable.loadingNetWork"
								:noDataFlag="dataTable.noDataFlag"
            />
        </div>
    </div>
</template>

<script setup>
    import { ref, reactive, toRefs, computed, onBeforeMount, watch, onMounted, nextTick } from 'vue'
		import { useIntersectionObserver } from '@vueuse/core';
    import TitleBox from '@/components/TitleBox.vue'
    import uiEchart from '@/components/ui-echart.vue'
    import { langTxt, getFilterThArr, getFilterLangArr } from '@/utils/util'
    // import { getPrescriptionOverall } from '@/service/tcm'
    import CombinationDiagram from '@/components/combinationDiagram.vue'
    import { controlStore } from '@/stores/control'
		import { getPrescrNetwork, getTableThList, prescNetworkTable } from '@/service/tcm'
		import { useRouter } from 'vue-router'

    import { debounce } from 'lodash'
    
    const emitter = defineEmits(['toCalc']);
		const router = useRouter();
		const networkDiv = ref(null);
    const props = defineProps({
        detailId: {
            type: [Number, String],
            default: ''
        }
    });
    const { detailId } = toRefs(props);
    
    let searchDebounce = null;

    const controlSto = controlStore();
    const selectTab = ref(0);
    const graphRange = ref([0, 1])
		const maxRange = ref(1);
		const condPage = reactive({
			pageSize: 10,
			pageNo: 1,
			total: 0
		})
    let dataGraph = reactive({
			data: [],
			links: [],
			diagramLenList: [],
			hotMapX: [],
			hotMapY: [],
			hotMapData: [],
			hotMaxRange: 2415
		});
    // let linksGraph = reactive();
    const uiCode = ref("overall_network"); //下载表格的code
		const uiCodeDowm = 'pre_network';
    const isLoading = ref(false);
    const dataTable = reactive({
			filterKey: 'pres_netwrok',
			dTablevt: 1,
			tableConfig: {
				'tooltip-effect': 'dark',
				'highlight-current-row': true,
				stripe: true,
				'header-cell-style': { background: '#BC9F77', color: '#FFF' },
			},
			columnConfig: [],
			dataList: [],
			templateList: [{
					idField: '100716826576557300'
				}, 
				{
					idField: '100716826576557301'
				},
				{
					idField: '100716826576557302'
				},
				{
					idField: '100716826576557303'
				},
			],
			para: {
				langCode:controlSto.language == 1 ? 'ENG': 'CHN',
				prescriptionId: detailId.value,
				uiTypeCode: uiCode.value
			},
			noDataFlag: true,
			loadingNetWork: false
		})
    const dragramTypeList = [
		{
			tname: 'Network',
			lgid: '-60',
			code: 'Network'
		}, {
			tname: 'Heatmap',
			lgid: '-61',
			code: 'Heatmap'
		}, {
			tname: 'Table',
			lgid: '-62',
			code: 'Table'
		}
	]
    
    const searchPlace = computed(() => {
		return langTxt(controlSto.language, '-15');
	});
   let stop;
    onMounted(()=> {
			const {stop} = useIntersectionObserver(
				networkDiv,
				([{ isIntersecting }], observerElement) => {
					if (isIntersecting) {
						
						// 停止监听，如果你只想知道一次可视性变化
						toGetTableThList();
						toGetStatistic();
						initDebounce();
						toGetData();
						//阻止再次请求
						stop()
					}
				},
				{
					threshold: 0, // 当交叉框达到视窗的这部分时触发
				}
			);
    });
    const changeShow = (item, index, isShow) => {
			// item.isShow = !item.isShow;
			dataGraph.diagramLenList[index].isShow = isShow;

		}
		const toClkItem = (rowItem, index) => {
			if (!index && index == 1) {
				//herb
				router.push({ name: 'herbdetail', query: {id: rowItem[dataTable.templateList[0].idField]} });
			} else {
				//成分
				router.push({ name: 'ingrdetail', query: {id: rowItem[dataTable.templateList[2].idField]} });
			}
		}
	const toGetTableThList = () => {
		let params = {
            uiCode: uiCode.value,
            langCode: 'ENG,CHN'
        };
		getTableThList(params).then(res => {
			if (res.success) {
						let arr = res.data || [];
						let thArr = getFilterThArr(arr, dataTable.filterKey);
						let langArr = getFilterLangArr(thArr);
						controlSto.setLangList(langArr);
						dataTable.columnConfig = thArr;
				}
		})
	}
	const changeSlider = (e) => {
		console.log(e, 'oooo')
		nextTick(() => {
			graphRange.value = e;
		})
	}
  const changeTabs = (item, index) => {
		selectTab.value = index;
		if(index == 0) {
			//关系图
			dataGraph.diagramLenList.forEach(e => {
				e.isShow = true;
			})
		} else if (index == 1) {
			//热力图
		} else if (index == 2) {
			//table
		}
	}
	const toGetStatistic = () => {
		dataTable.loadingNetWork = true;
		getPrescrNetwork({
			langCode: controlSto.language == 1 ? 'ENG' : 'CHN',
			prescriptionId: detailId.value,
			uiTypeCode: uiCode.value
		}).then(res => {
			if (res.success && res.data) {
				dataTable.loadingNetWork = false;
				if (res.data.scatterDiagram) {
					const scatterDiagram = res.data.scatterDiagram;
					if(scatterDiagram.nodeList.length == 0) dataTable.noDataFlag = true;
					else dataTable.noDataFlag = false;

					if (scatterDiagram.links && scatterDiagram.nodeList) {
						let arrXy = [], xyData = [];
						scatterDiagram.links.forEach((e, indx) => {
							if (!indx) {
								maxRange.value = Number(e.distance);
							} else if (maxRange.value < Number(e.distance)) maxRange.value = Number(e.distance);
							graphRange.value = [0, maxRange.value];
							dataGraph.hotMaxRange = maxRange.value;
							// dataGraph.hotMaxRange = 2415;
							scatterDiagram.nodeList.forEach((o, index) => {
								arrXy.push(o.name)
								if (e.source == o.id) e.sourceCategory = o.category;
								if (e.target == o.id) e.targetCategory = o.category;
								o.symbolSize = 10;
								// if (o.category == 2) {
								// 		o.symbolSize = 20;
								// 	} else if (o.category == 3) {
								// 		o.symbolSize = 15
								// 	}
								if (!index) {
									o.y = (e.distance * 10) * (Math.floor(Math.random() * (Math.floor(200) + Math.floor(120) + 4)));
									o.x = -(e.distance * 10) * (Math.floor(Math.random() * (Math.floor(200) + Math.floor(120) + 5)));
								}
								if (!o.x && index) {
									o.y = (e.distance * 10) * (Math.floor(Math.random() * (Math.floor(200) + Math.floor(index) + index)));
									o.x = -(e.distance * 10) * (Math.floor(Math.random() * (Math.floor(200) + Math.floor(index) + index)));
								}
								//线的颜色
								if (e.source ==  o.id && o.category == 2) {
										e.lineStyle = {
											color: '#138848',
											width: 1
										}
								} else if (e.source ==  o.id && o.category == 3) {
									e.lineStyle = {
										color: '#1677FF',
										width: 1
									} 
								} else if (e.source ==  o.id && o.category == 1) {
									e.lineStyle = {
										color: '#BC9F77',
										width: 1
									}
								} else if (e.source ==  o.id && o.category == 4) {
									e.lineStyle = {
										color: '#02BCD5',
										width: 1
									}
								}
								//元素的颜色
								if (o.category == 2) {
										o.itemStyle = {
											color: '#138848'
										}
									} else if(o.category == 3) {
										o.itemStyle = {
											color: '#1677FF'
										}
									} else if(o.category == 1) {
										o.itemStyle = {
											color: '#BC9F77'
										}
									} else if(o.category == 4) {
										o.itemStyle = {
											color: '#02BCD5'
										}
									}
							})
						})
						dataGraph.data = scatterDiagram.nodeList;
						dataGraph.links = scatterDiagram.links;
					
						//处理heatmap数据；
						let _arrXy = new Set(arrXy)
						arrXy = [..._arrXy]
						arrXy.forEach((ex, xind) => {
							arrXy.forEach((ey, yind) => {
								let id1 = '', id2 = '';
								scatterDiagram.nodeList.forEach((enode, nodeind) => {
									if(ex == enode.name) id1 = enode.id;
									if(ey == enode.name) id2 = enode.id;
									
								})
								if (id1 && id2){
									scatterDiagram.links.forEach((elink, linkInd)=> {
										if (id1 == elink.source && elink.target == id2) {
											xyData.push([xind, yind, elink.distance])
											id1 = '';
											id2 = '';
										}
									})
								}
							})
						});
						dataGraph.hotMapData = xyData;
						dataGraph.hotMapX = arrXy.reverse();
						dataGraph.hotMapY = arrXy;
					}
					if(scatterDiagram.contractlist) {
						//diagramLenList
						scatterDiagram.contractlist.forEach((e, index) => {
							e.isShow = true;
							e.id = 'pre_' + index;
							e.source = {
								code: e.sourceCategory,
								name: e.sourceName
							}
							e.target = {
								code: e.targetCategory,
								name: e.targetName
							}
						});
						dataGraph.diagramLenList = scatterDiagram.contractlist
					}
				}
			}
		}).catch((err) => {
				dataTable.noDataFlag = true;
				dataTable.loadingNetWork = false;
			})
	}
	const getTableData = () => {
		isLoading.value = true;
		prescNetworkTable({
			langCode: controlSto.language == 1 ? 'ENG' : 'CHN',
			prescriptionId: detailId.value,
			uiTypeCode: uiCode.value,
			pageSize: condPage.pageSize,
			pageNo: condPage.pageNo
		}).then(res => {
			isLoading.value = false;
			if (res.success && res.data && res.data.records) {
				dataTable.dataList = res.data.records || [];
				condPage.total = res.data.totalCount || 0;
			}
		}).catch(err => {
			isLoading.value = false;
		})
	}
	const chgSize = (e) => {
		condPage.pageSize = e || 10;
    getTableData();
	}
	const chgCurrnt = (e) => {
		condPage.pageNo = e || 1;
    getTableData();
	}

	const initDebounce = () => {
			searchDebounce = debounce((e) => {
				toGetStatistic();
				getTableData();
			}, 400);
	};

	const toGetData = () => {
			searchDebounce && searchDebounce();
	};

	watch(() => controlSto.language, (n, v) => {
		if (n != v && v) {
			toGetStatistic();
			getTableData();
		}
	})

</script>


<style lang="scss" scoped>
    .pres-land-overall-comp {
        .switch-cont-box {
            .chart-img {
                height: 360px;
                width: 100%;
            }
        }
        .cont-box {
            margin-top: 32px;
            // height: 360px;
            // .page-box {
            //     padding: 10px 0;
            // }
            .plane-box {
                padding-top: 32px;
            }
            .switch-box {
				padding-bottom: 32px;
				text-align: center;
				.switch-wrap {
					display: inline-block;
					border: 1px solid #BC9F77;
					border-radius: 30px;
					font-size: 0;
					color: #967846;
					.switch-item {
						display: inline-block;
						height: 40px;
						width: 200px;
						padding: 0 32px;
						line-height: 40px;
						border-right: 1px solid #BC9F77;
						font-weight: 600;
						font-size: 18px;
						cursor: pointer;
						&:first-child {
							// border-radius: 30px;
							border-top-left-radius: 16px;
							border-bottom-left-radius: 16px;
						}
						&:last-child {
							border-right: none;
							border-top-right-radius: 16px;
							border-bottom-right-radius: 16px;
						}
						&.switch-item-on {
							color: #fff;
							background-color: #BC9F77;
						}
					}
				}

			}
        }
    }
</style>
